﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Metadata.Entity.ScheduleJob;
using T.FAS.Runtime.ScheduleJob.SPI;
using TriggerType = T.FAS.Runtime.Metadata.Entity.ScheduleJob.TriggerType;

namespace T.FAS.Runtime.ScheduleJob.Service
{
    public class ScheduleJobWrapper
    {
        public static ScheduleJobInstanceStore WrapScheduleJobInstance(ScheduleJobExecContext context)
        {
            if (context == null)
                return null;
            return new ScheduleJobInstanceStore()
            {
                ID = Guid.NewGuid().ToString(),
                InstanceID = context.Instance.ID,
                Name = context.ScheduleJobMetaData.Name+context.Instance.ID,
                Description =context.ScheduleJobMetaData.Description,
                ScheduleJobID = context.ScheduleJobMetaData.ID,
                ScheduleJobType = context.ScheduleJobMetaData.JobType,
                ScheduleJobGroup = context.ScheduleJobMetaData.ScheduleGroup,
                ScheduleJobData = JsonConvert.SerializeObject(context.Instance.Data),
                ScheduleJobExecuteState = JobExecuteState.New,
                ScheduleJobExecuteResult = JobExecuteResult.None,
                FailReason ="",
                UserID = context.Instance.UserID,
                UserName = context.Instance.UserName,
                TriggerID = context.ScheduleJobMetaData.ScheduleTrigger.ID,
                TriggerType = context.ScheduleJobMetaData.ScheduleTrigger.TriggerType,
                CronExpression = context.ScheduleJobMetaData.ScheduleTrigger.CronExpression,
                Ext1 = "",
                Ext2 = "",
                Ext3 = "",
                Creator = context.Instance.UserID,
                CreateTime = DateTime.Now,
                LastModifier = context.Instance.UserID,
                LastModifyTime = DateTime.Now
            };
        }
        public static ScheduleJobInstanceStore WrapScheduleJobInstance(ScheduleJobInstance instance)
        {
            var context = ScheduleJobExecuteContextBuilder.Build(instance);
            return WrapScheduleJobInstance(context);

        }
        public static ScheduleJobInstance WrapScheduleJobInstanceStore(ScheduleJobInstanceStore store)
        {
            if (store == null)
                return null;
            var instance = new ScheduleJobInstance()
            {
                ID = store.InstanceID,
                ScheduleJobID = store.ScheduleJobID,
                UserID = store.UserID,
                UserName = store.UserName,
                ScheduleJobGroup = store.ScheduleJobGroup
            };
            instance.Data = JsonConvert.DeserializeObject<ScheduleJobDataMap>(store.ScheduleJobData);

            return instance;
        }

        public static List<ScheduleJobInstance> WrapScheduleJobSubscription(ScheduleJobSubscription subscription)
        {
            if (subscription == null || subscription.ExecuteFrequency == null)
                return null;
            var list = new List<ScheduleJobInstance>();
            if (subscription.ExecuteFrequency.FrequencyType == FrequencyType.SysFrequency)
            {
                if (subscription.ExecuteFrequency.SysFrequencies == null || subscription.ExecuteFrequency.SysFrequencies.Count <= 0)
                    return null;
                subscription.ExecuteFrequency.SysFrequencies.ForEach(f =>
                {
                    var instance = new ScheduleJobInstance();
                    instance.ScheduleJobID = subscription.ID;
                    instance.ScheduleJobGroup = subscription.BusinessType;
                    instance.UserID = subscription.OwnerID;
                    instance.UserName = subscription.OwnerName;
                    instance.ScheduleJobMetadata = new Metadata.Entity.ScheduleJob.ScheduleJob()
                    {
                        ID = subscription.ID,
                        Code = subscription.Code,
                        Name = subscription.Name,
                        BusinessType = subscription.BusinessType,
                        ScheduleGroup = subscription.BusinessType,
                        JobType = Metadata.Entity.ScheduleJob.JobType.Subscription,
                        Description = subscription.Description,
                        IsPersistent = true,
                        IsAutoRecovery = true,
                        IsAllowConcurrentExecution = false,
                        JobContent = subscription.JSContent,//这里需要一个服务端可执行的js脚本
                        IsDisabled = false,
                        IsSysDefault = false,
                        EnableLog = true,
                        EnableMonitor = true,
                        FailureStrategy = FailureStrategy.FailRetry,
                        RepeatCount = 0,
                        RepeatInterval = 0,
                    };
                    instance.ScheduleJobMetadata.ScheduleTrigger = new ScheduleTrigger()
                    {
                        ID = Guid.NewGuid().ToString(),
                        Code = subscription.Code + "SubTrigger",
                        Name = subscription.Name + "SubTrigger",
                        Description = subscription.Description,
                        TriggerGroup = subscription.BusinessType,
                        TriggerType = TriggerType.Schedule,
                        RepeatCount = 3,
                        RepeatInterval = 5,
                        Priority = 1,
                        CronExpression = f.CronExpression,
                        EffectiveTime = DateTime.Now,
                        ExpiredTime = DateTime.Now.AddYears(10),
                        IsSysDefault = false,
                        MisfirePolicy = MisfirePolicy.Schedule_IgnoreMisfire,
                        DelayTime = 0
                    };
                    instance.Data = new ScheduleJobDataMap();
                    instance.Data.AddJsonData(JsonConvert.SerializeObject(subscription));
                    list.Add(instance);
                });
            }
            else
            {
                var instance = new ScheduleJobInstance();
                instance.ScheduleJobID = subscription.ID;
                instance.ScheduleJobGroup = subscription.BusinessType;
                instance.UserID = subscription.OwnerID;
                instance.UserName = subscription.OwnerName;
                instance.ScheduleJobMetadata = new Metadata.Entity.ScheduleJob.ScheduleJob()
                {
                    ID = subscription.ID,
                    Code = subscription.Code,
                    Name = subscription.Name,
                    BusinessType = subscription.BusinessType,
                    ScheduleGroup = subscription.BusinessType,
                    JobType = Metadata.Entity.ScheduleJob.JobType.Subscription,
                    Description = subscription.Description,
                    IsPersistent = true,
                    IsAutoRecovery = true,
                    IsAllowConcurrentExecution = false,
                    JobContent = subscription.JSContent,//这里需要一个服务端可执行的js脚本
                    IsDisabled = false,
                    IsSysDefault = false,
                    EnableLog = true,
                    EnableMonitor = true,
                    FailureStrategy = Metadata.Entity.ScheduleJob.FailureStrategy.FailRetry,
                    RepeatCount = 0,
                    RepeatInterval = 0,
                };
                instance.ScheduleJobMetadata.ScheduleTrigger = new Metadata.Entity.ScheduleJob.ScheduleTrigger()
                {
                    ID = Guid.NewGuid().ToString(),
                    Code = subscription.Code + "SubTrigger",
                    Name = subscription.Name + "SubTrigger",
                    Description = subscription.Description,
                    TriggerGroup = subscription.BusinessType,
                    TriggerType = Metadata.Entity.ScheduleJob.TriggerType.Schedule,
                    RepeatCount = 3,
                    RepeatInterval = 5,
                    Priority = 1,
                    CronExpression = subscription.ExecuteFrequency.CronExpression,
                    EffectiveTime = DateTime.Now,
                    ExpiredTime = DateTime.Now.AddYears(10),
                    IsSysDefault = false,
                    MisfirePolicy = Metadata.Entity.ScheduleJob.MisfirePolicy.Schedule_IgnoreMisfire,
                    DelayTime = 0
                };
                instance.Data = new ScheduleJobDataMap();
                instance.Data.AddJsonData(JsonConvert.SerializeObject(subscription));
                list.Add(instance);
            }
            return list;
        }
    }
}
